package com.crk.shixiguanli.service.impl;



import com.crk.shixiguanli.dao.RoleAuthDao;
import com.crk.shixiguanli.dao.RoleDao;
import com.crk.shixiguanli.dao.StudentDao;
import com.crk.shixiguanli.dao.UserDao;
import com.crk.shixiguanli.entity.Role;
import com.crk.shixiguanli.entity.RoleAuth;
import com.crk.shixiguanli.entity.Student;
import com.crk.shixiguanli.entity.User;
import com.crk.shixiguanli.service.RoleAuthService;
import com.crk.shixiguanli.service.UserService;
import com.crk.shixiguanli.util.Page;
import com.crk.shixiguanli.util.ResponseEnum;
import com.crk.shixiguanli.util.ResponseResult;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Author: 程荣凯
 * @Date: 2019/2/27 14:47
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {
    /**
     * 用户操作
     */
    @Autowired
    UserDao userDao;
    @Autowired
    RoleAuthService roleAuthService;
    @Autowired
    RoleDao roleDao;
    @Autowired
    RoleAuthDao roleAuthDao;
    @Autowired
    StudentDao studentDao;



    private final static String DEFAULT_PWD = "123456";

    /**
     * 获取所有用户
     *
     * @return 用户列表
     */
    @Override
    public List<User> getAllUser() {
        return userDao.selectAll();
    }

    /**
     * 保存用户
     *
     * @param user 用户对象
     * @return
     */
    @Override
    public ResponseResult saveUser(User user) {
        if (null != user){
            int result = 0;
            if(user.getId() == null){
                user.setCreateTime(new Date());
                user.setCreator(1);
                user.setUpdateTime(new Date());
                user.setUpdator(1);
                user.setStatus((short)1);
                user.setPwd(DEFAULT_PWD);
                user.setSalt(UUID.randomUUID().toString());
                result = userDao.insert(user);
            }else{
                user.setUpdateTime(new Date());
                User userinfo = (User) SecurityUtils.getSubject().getPrincipal();
                user.setUpdator(userinfo.getId());
                result = userDao.updateByPrimaryKey(user);

            }
            if (result>0){
                return ResponseResult.success(user);
            }else{
                return ResponseResult.fail();
            }
        }else {
            return ResponseResult.fail();
        }
    }

    /**
     * 根据用户名或手机号查询用户信息
     *
     * @param userName 用户名或手机号
     * @return
     */
    @Override
    public ResponseResult getUserByNameOrPhone(String userName) {
        return null;

    }




    /**
     * @param userId
     * @param status
     * @return
     */
    @Override
    public ResponseResult changeStatus(Integer userId, Integer status) {
        int result = userDao.changeStatus(userId,status);
        if (result>0){
            return ResponseResult.success();
        }else{
            return ResponseResult.fail();
        }
    }


    /**
     * 修改密码
     *
     * @param oldPwd 旧密码
     * @param newPwd 新密码
     * @return
     */
    @Override
    public ResponseResult changePassword(String oldPwd, String newPwd) {
        User userInfo = (User) SecurityUtils.getSubject().getPrincipal();
        if (!oldPwd.equals(userInfo.getPwd())){
            return ResponseResult.fail(ResponseEnum.OLDPWD_ERROR);
        }
        userInfo.setUpdateTime(new Date());
        userInfo.setUpdator(userInfo.getId());
        userInfo.setPwd(newPwd);
        int count = userDao.updateByPrimaryKey(userInfo);
        if (count>0){
            return ResponseResult.success();
        }else{
            return ResponseResult.fail();
        }
    }

    /**
     * 删除用户
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult deleteUser(Integer userId) {
        int result = userDao.deleteByPrimaryKey(userId);
        if (result > 0){
            return ResponseResult.success();
        }else{
            return ResponseResult.fail();
        }
    }

    /**
     * 查询用户列表（分页）
     *
     * @param userName
     * @param orderBy
     * @param currentPage
     * @param size
     * @return
     */
    @Override
    public ResponseResult getSysUserList(String userName,String keyword, String orderBy,String userType, Integer currentPage, Integer size) {
        Integer count = userDao.countSysUserList(userName,keyword,userType);
        Page page = new Page();
        page.setAllRow(count);
        page.setCurrentPage(currentPage);
        page.setSize(size);
        List<User> userList = userDao.getSysUserList(userName,keyword,userType,orderBy,page.getStart(),page.getSize());
        return ResponseResult.success(userList,page);
    }

    /**
     * 根据ID查询用户
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult getSysUserById(Integer userId) {
        User user = userDao.getSysUserById(userId);
        return ResponseResult.success(user);
    }

    /**
     * 重置密码
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult resetPwd(Integer userId) {
        User userInfo = (User) SecurityUtils.getSubject().getPrincipal();

        User user = new User();
//        String salt =EncryptedUtil.getSalt();
//        String pwd = EncryptedUtil.generate(EncryptedUtil.md5Hex(DEFAULT_PWD),salt);
//        user.setSalt(salt);
//        user.setPwd(pwd);
        user.setId(userId);
        user.setUpdator(userInfo.getId());
        user.setUpdateTime(new Date());
        int count = userDao.updateByPrimaryKey(user);
        if (count>0){
            return ResponseResult.success();
        }else{
            return ResponseResult.fail();
        }
    }

    /**
     * 根据用户ID查询包含的角色列表
     *
     * @param id
     * @return
     */
    @Override
    public List<Role> getRoleList(Integer id) {
        return userDao.getRoleList(id);
    }

    /**
     * 根据用户名查询用户
     *
     * @param userName
     * @return
     */
    @Override
    public User findByUsername(String userName) {
        return userDao.findByUsername(userName);
    }




    /**
     * 根据用户类型查询角色ID
     * @param userType
     * @return
     */
    private Integer getRoleByType(Integer userType){
        String roleCode = "doctor";
        switch (userType){
            case 1:roleCode = "doctor";break;
            case 2:roleCode = "patient";break;
        }
        Role roleByCode = roleDao.getRoleByCode(roleCode);
        return roleByCode.getId();
    }

    @Override
    public User getUserByIdCard(String idCard) {
        return userDao.getUserByIdCard(idCard);
    }

    @Override
    public ResponseResult register(String userName, String phone, String email, String pwd, String userType,String idCard) {
//        用户注册
        User sysUser = new User();
        sysUser.setUserName(userName);
        sysUser.setPhone(phone);
        sysUser.setEmail(email);
        sysUser.setPwd(pwd);
        sysUser.setCreator(1);
        sysUser.setUpdator(1);
        sysUser.setStatus((short)1);
        sysUser.setUserType(userType);
        if (userType.equals("student")){
            if (StringUtils.isEmpty(idCard)){
                return ResponseResult.fail();
            }
//            根据学生表检验学生信息是否存在
            Student studentByIdCard = studentDao.getStudentByIdCard(idCard);
            if (null == studentByIdCard){
                return ResponseResult.fail(ResponseEnum.IDCARD_CONFIG_ERROR);
            }
            sysUser.setIdCard(idCard);
        }

        sysUser.setSalt(UUID.randomUUID().toString());
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateTime(new Date());
        int userResult = userDao.insert(sysUser);
        if (userResult == 0){
            return ResponseResult.fail();
        }
//        分配角色
        ResponseResult result = roleGenerator(sysUser.getId(), userType);
        return result;
    }

    /**
     * 分配角色
     * @param userId 用户ID
     * @param userType 用户类型
     * @return
     */
    private ResponseResult roleGenerator(int userId,String userType){
        Role sysRole = roleDao.getRoleByCode(userType);
        if (sysRole == null){
            return ResponseResult.fail(ResponseEnum.ROLE_CONFIG_ERROR);
        }
        RoleAuth sysRoleAuth = new RoleAuth();
        sysRoleAuth.setPartyId(userId);
//        类型为1表明是用户权限
        sysRoleAuth.setPartyType((short)1);
        sysRoleAuth.setRoleId(sysRole.getId());
        sysRoleAuth.setStatus((short)1);
        sysRoleAuth.setCreator(1);
        sysRoleAuth.setUpdator(1);
        sysRoleAuth.setCreateTime(new Date());
        sysRoleAuth.setUpdateTime(new Date());
        int roleAuthResult = roleAuthDao.insert(sysRoleAuth);
        if (roleAuthResult == 0){
            return ResponseResult.fail();
        }
        return ResponseResult.success();
    }


}
